<?php

class GalleryController extends AbstractAdminController
{

	public function actionList($categoryId = null)
	{
		$oGallery = new Gallery();
		$oRowset = $oGallery->getAll($this->oPager, $categoryId);

		$this->layout='//layouts/admin';
		$this->render('list', array(
		                           'oRowset' => $oRowset,
		                           'categoryId' => $categoryId
		                      ));
	}

	public function actionEditor($categoryId = null)
	{
		$toView = array();

		$oGallery = new Gallery();
		$oPhotos = new Photos();

		$id = $this->_getParam('id');

		if($id > 0)
			$oGallery = $oGallery->findByPk($id);

		if($this->_isPost())
		{
			$attr = $this->_getPost();
//			print_r($attr); exit;

			if(!$oGallery || !$oGallery->id)
			{
				$oGallery = new Gallery();

				$attr['user_add'] = $this->_userInfo->id;
				$attr['date_add'] = date('Y-m-d H:i:s');
			}
			else
			{
				$attr['user_edit'] = $this->_userInfo->id;
				$attr['date_edit'] = date('Y-m-d H:i:s');
			}

			if(!empty($attr['title']))
				$attr['alias'] = $oGallery->generateAlias(($oGallery && $oGallery->id ? $oGallery->id : null), $attr['title']);

			$attr['active'] = 1;
			$attr['is_main'] = !empty($attr['is_main']) ? 1 : 0;

//	        print_r($attr); exit;
			$oGallery->setAttributes($attr);

//			print_r($oGallery); exit;
			if($oGallery->save(false))
			{
				$oPhotos->saveByTarget($oGallery, $this->_getPost());

				return $this->redirect(Yii::app()->createUrl('/admin/gallery/list'));
			}
		}

		if($oGallery)
			$oPhotos->selectAllByRow($oGallery);

		$toView['oRow'] = $oGallery;
		$toView['categoryId'] = $categoryId;

		$this->render('edit', $toView);
	}

	public function actionDelete($id = null)
	{
        $oGallery = new Gallery();
        $oPhoto = new Photos();
        $oFiles = new Files();

        $oGallery = $oGallery->findByPk($id);

        $oPhoto->selectByRow($oGallery);

        if(!empty($oGallery) && !empty($oGallery['photos']))
        {
            foreach($oGallery['photos'] as $oPhoto)
            {
                $oFiles->deleteDirectory(PUBLIC_PATH . $oPhoto->path);

                $oPhoto->delete();
            }
        }

        $oGallery->delete();

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
	}

	public function actionActive($id = null)
	{
		if($id < 1)
			exit;

        $oGallery = new Gallery();

        $oGallery = $oGallery->findByPk($id);

		$oGallery->updateAll(array('active' => !$oGallery->active), "id = '". $id ."'");

        $returnUrl = Yii::app()->user->returnUrl;

        if(!empty($_SERVER['HTTP_REFERER']))
            $returnUrl = $_SERVER['HTTP_REFERER'];

        return $this->redirect($returnUrl);
	}

}